package com.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * This class helps open, create, and upgrade the database file.
 */
public class DatabaseHelper extends SQLiteOpenHelper {

	private static final String TAG = "DatabaseHelper";
	
	public static final int DATABASE_VERSION = 8;
	
	//private Context mContext;
	
    DatabaseHelper(Context context) {
        super(context, MyDatabase.DATABASE_NAME, null, DATABASE_VERSION);
        //this.mContext = context;
    }

    /**
     * Called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
    	
    	Log.i(TAG, "onCreate");
        db.execSQL("CREATE TABLE " + MyDatabase.USER_TABLE_NAME + " ("
                + "_id INTEGER PRIMARY KEY autoincrement,"
                + ColumnsUser.ID + " Text,"
                + ColumnsUser.NAME + " Text,"
                + ColumnsUser.AGE + " INTEGER,"
                + ColumnsUser.GENDER + " Text"
                + ");");
        
        
        db.execSQL("CREATE TABLE " + MyDatabase.USER_DESC_TABLE_NAME + " ("
                + "_id INTEGER PRIMARY KEY autoincrement,"
                + ColumnsUserDesc.ID + " Text,"
                + ColumnsUserDesc.DESC + " Text"
                + ");");
        
        
        insertUser(db,"happy","김철수",22,"M");
        insertUser(db,"shop","박보람",23,"W");
        insertUser(db,"wiz","신민철",27,"M");
        insertUserDesc(db,"happy","멋쟁이 친구입니다.");
        insertUserDesc(db,"shop","참신한 얼굴입니다.");
        insertUserDesc(db,"wiz","약간 올드한 얼굴입니다.");
        
        createIndexes(db);
    }
    

    private void insertUser(SQLiteDatabase db, String UserId, String UserName, Integer UserAge, String UserGender) {
    	String sql = "INSERT INTO " + MyDatabase.USER_TABLE_NAME + "(id,name,age,gender) VALUES ('"+UserId+"', '"+UserName+"', "+UserAge+", '"+UserGender+"');";
    	Log.i(TAG, "sql");
    	db.execSQL(sql);
    }
    
    private void insertUserDesc(SQLiteDatabase db, String UserId, String UserDesc) {
    	String sql = "INSERT INTO " + MyDatabase.USER_DESC_TABLE_NAME + "(id,desc) VALUES ('"+UserId+"', '"+UserDesc+"');";
    	Log.i(TAG, "sql");
    	db.execSQL(sql);
    }
    

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.i(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ".");
        createIndexes(db);
    }
    
    private void createIndexes(SQLiteDatabase db) {
    	db.execSQL("create index "+MyDatabase.USER_TABLE_NAME+
     		   "_idx1 on "+
     		  MyDatabase.USER_TABLE_NAME+" ("+ColumnsUser.ID+");");    	
    }
}
